'use strict';

angular.module('snPaas_om').service('logStore',['$http','$q','baseUrl','$timeout',function($http,$q,baseUrl,$timeout){
	

   var offset = 0;
   var isEnd = false;
   var endFlag = 1;
   var logStack = [];
   var logSpeed = 50;
	var getLog = function(taskId){
		offset = 0;
		endFlag = 1;
		isEnd = false;
		var deferred = $q.defer();
		var getLogFn = function(tId){

			$http.get('/rest/cluster/deployingLog',{params:{taskId:tId,offset:offset}}).success(function(data){
				var d  = data.data||{};
				offset = d.offset||0;
				var log = d.log||[];
				if(log.length >0){
					if(log[log.length-1].flag >2){
						endFlag = log[log.length-1].flag;
						isEnd = true;
					}
					for(var i = 0,l = log.length;i<l;i++){
						if(log[i].flag ==2){
							var tmp  = log[i].message.split('\n');
							for(var j=0,ll = tmp.length;j<ll;j++){
								logStack.push({message:tmp[j],flag:2});
							}
							continue;
						}
						else{
							logStack.push(log[i]);
						}
					}
					if(!isEnd){
						getLogFn(taskId);
					}
				}
				else{
					$timeout(function(){
						getLogFn(taskId);
					},500);
				}
				
				
			});

		};
		var postLog = function(){
			if(logStack.length>0){
				var item = logStack.shift();
				deferred.notify(item);
				$timeout(function(){
					postLog();
				},logSpeed);
			}
			else{
				if(!isEnd){
					$timeout(function(){
						postLog();
					},logSpeed);
				}
				else{
					if(endFlag ==3){
						deferred.resolve('部署成功');
					}
					else if(endFlag ==4){
						deferred.reject('部署失败');
					}
					else if(endFlag ==5){
						deferred.reject('部署被取消');

					}
					
				}
			}
		};
		getLogFn(taskId);
		postLog();
		return deferred.promise;
	};
	var getMysqlList = function(deployId){
		var deferred = $q.defer();
		$http.get('/rest/cluster/listTasksInfo',{params:{deployId:deployId,type:2}}).success(function(data,status){
			deferred.resolve(data.data);
		});
		return deferred.promise;
	};
	var getCfList = function(deployId){
		var deferred = $q.defer();
		$http.get('/rest/cluster/listTasksInfo',{params:{deployId:deployId,type:1}}).success(function(data,status){
			deferred.resolve(data.data);
		});
		return deferred.promise;
	};
	return {
		'getLog':getLog,
		getMysqlList:getMysqlList,
		getCfList:getCfList
	};
}]);